package com.quectel.core.module.partybuilding.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dao.PartyOrganizationBuildingDao;
import com.quectel.core.module.partybuilding.dao.PartyOrganizationDao;
import com.quectel.core.module.partybuilding.dao.PartyOrganizationUnitDao;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationBuildingDto;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationUnitDto;
import com.quectel.core.module.partybuilding.entity.PartyOrganizationBuildingEntity;
import com.quectel.core.module.partybuilding.entity.PartyOrganizationEntity;
import com.quectel.core.module.partybuilding.entity.PartyOrganizationUnitEntity;
import com.quectel.core.module.partybuilding.service.PartyOrganizationBuildingService;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyOrganizationUnitService;
import com.quectel.core.module.really.dto.ReallyCompanyDto;
import com.quectel.core.module.really.service.ReallyCompanyService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:17
 */
@DubboService
public class PartyOrganizationServiceImpl implements PartyOrganizationService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyOrganizationServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_ORGANIZATION_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_ORGANIZATION_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyOrganizationDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_ORGANIZATION_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyOrganizationDao partyOrganizationDao;
    @Autowired
    private PartyOrganizationBuildingDao partyOrganizationBuildingDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyOrganizationBuildingService partyOrganizationBuildingService;
    @Autowired
    private PartyOrganizationUnitService partyOrganizationUnitService;
    @Autowired
    private PartyOrganizationUnitDao partyOrganizationUnitDao;
    @Autowired
    private ReallyCompanyService reallyCompanyService;
    @Autowired
    private VillageBuildingService villageBuildingService;

    @Override
    public PartyOrganizationDto selectByName(Long tenantId, String name) {
        PartyOrganizationEntity entity = partyOrganizationDao.selectOne(
                new LambdaQueryWrapper<PartyOrganizationEntity>()
                        .eq(PartyOrganizationEntity::getTenantId, tenantId)
                        .eq(PartyOrganizationEntity::getName, name)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );

        return CopyUtils.copyObj(entity, PartyOrganizationDto.class);
    }

    /**
     * @param partyOrganizationDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(PartyOrganizationDto partyOrganizationDto) {
        if (partyOrganizationDto.getId() == null) {
            Long id = save(partyOrganizationDto);
            partyOrganizationDto.setId(id);
        } else {
            updateById(partyOrganizationDto);
        }

        // 删除单位绑定关系
        partyOrganizationUnitDao.delete(new LambdaQueryWrapper<PartyOrganizationUnitEntity>()
                .eq(PartyOrganizationUnitEntity::getPartyId, partyOrganizationDto.getId()));

        // 绑定单位绑定关系
        for (ReallyCompanyDto companyDto : partyOrganizationDto.getCompanyList()) {
            PartyOrganizationUnitDto unitDto = new PartyOrganizationUnitDto();
            unitDto.setId(Snowflake.nextId());
            ReallyCompanyDto company = reallyCompanyService.selectCacheById(companyDto.getId());
            if (company != null){
                unitDto.setTenantId(company.getTenantId());
                unitDto.setVillageId(company.getVillageId());
            }
            unitDto.setUnitId(companyDto.getId());
            unitDto.setPartyId(partyOrganizationDto.getId());
            partyOrganizationUnitService.save(unitDto);
        }

        // 删除楼栋绑定关系
        partyOrganizationBuildingDao.delete(new LambdaQueryWrapper<PartyOrganizationBuildingEntity>()
                .eq(PartyOrganizationBuildingEntity::getPartyId, partyOrganizationDto.getId()));

        // 绑定组织和楼栋关系
        for (VillageBuildingDto buildingDto : partyOrganizationDto.getVillageBuildingList()) {
            PartyOrganizationBuildingDto savely = new PartyOrganizationBuildingDto();
            savely.setId(Snowflake.nextId());
            VillageBuildingDto villageBuildingDto = villageBuildingService.selectCacheById(buildingDto.getId());
            if (villageBuildingDto != null){
                savely.setTenantId(villageBuildingDto.getTenantId());
                savely.setVillageId(villageBuildingDto.getVillageId());
            }
            savely.setBuildingId(villageBuildingDto.getId());
            savely.setPartyId(partyOrganizationDto.getId());
            partyOrganizationBuildingService.save(savely);
        }
    }

    @Override
    public PartyOrganizationDto selectByCode(String code, Long tenantId) {
        PartyOrganizationEntity partyOrganizationEntity = partyOrganizationDao.selectOne(new LambdaQueryWrapper<PartyOrganizationEntity>()
                .eq(PartyOrganizationEntity::getCode, code)
                .eq(PartyOrganizationEntity::getTenantId, tenantId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        return CopyUtils.copyObj(partyOrganizationEntity, PartyOrganizationDto.class);
    }

    @Override
    public List<PartyOrganizationDto> recursion(Long id) {
        List<PartyOrganizationEntity> entities = partyOrganizationDao.recursion(id);
        List<PartyOrganizationDto> partyOrganizationDtos = CopyUtils.copyList(entities, PartyOrganizationDto.class);
        partyOrganizationDtos.forEach(this::paddingField);
        return partyOrganizationDtos;
    }

    @Override
    public PartyOrganizationDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_ORGANIZATION_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyOrganizationDto selectById(Long id){
            PartyOrganizationEntity entity = partyOrganizationDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyOrganizationDto.class));
    }

    @Override
    public List<PartyOrganizationDto> queryList(Map<String,Object> params){
        List<PartyOrganizationEntity> list = partyOrganizationDao.queryList(params);
        List<PartyOrganizationDto> result =  CopyUtils.copyList(list,PartyOrganizationDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyOrganizationDto paddingField(PartyOrganizationDto dto){
        if (dto != null){
            if (dto.getParentId()!=null){
                PartyOrganizationDto organizationDto = partyOrganizationService.selectCacheById(dto.getParentId());
                if (organizationDto!=null){
                    dto.setParentName(organizationDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyOrganizationDao.queryTotal(params);
    }

    @Override
    public Long save(PartyOrganizationDto dto){
        PartyOrganizationEntity entity = CopyUtils.copyObj(dto,PartyOrganizationEntity.class);
        entity.setId(Snowflake.nextId());
        partyOrganizationDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyOrganizationDto dto){
        PartyOrganizationEntity entity = CopyUtils.copyObj(dto,PartyOrganizationEntity.class);

        partyOrganizationDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyOrganizationDto dto) {
       PartyOrganizationEntity entity = CopyUtils.copyObj(dto,PartyOrganizationEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyOrganizationDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyOrganizationDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
